/**
 * 
 */
package cas.server.ldap.authe.compare;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.directory.api.ldap.model.constants.LdapSecurityConstants;
import org.apache.directory.api.ldap.model.password.EncryptionMethod;
import org.apache.directory.api.ldap.model.password.PasswordUtil;

import cas.server.ldap.authe.decode.CredentialDecoder;

/**
 * @author Cre.Gu
 *
 */
public class HashStringCredentialCompare implements StringCredentialCompare {

	private final List<CredentialDecoder> decoderList;

	public HashStringCredentialCompare(List<CredentialDecoder> decoders) {
		this.decoderList = new LinkedList<CredentialDecoder>();
		decoderList.addAll(decoders);
	}

	@Override
	public boolean compare(String credential, byte[] stored) {
		for (CredentialDecoder decoder : decoderList) {
			boolean flag = Arrays.equals(decoder.decode(credential),
					realStored(stored));

			if (flag)
				return flag;
		}

		return false;
	}

	private byte[] realStored(byte[] storedCredentials) {
		byte[] encryptedStored = storedCredentials;

		LdapSecurityConstants algorithm = PasswordUtil
				.findAlgorithm(storedCredentials);

		if (algorithm != null) {
			encryptedStored = PasswordUtil.splitCredentials(storedCredentials,
					new EncryptionMethod(algorithm, null));
		}
		return encryptedStored;
	}

}
